﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Transaction.recJurnalhandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using SIPO.Library.DataAccess.Transaction;
using SIPO.Library.DomainObject.Transaction;
using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;

using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.DataAccess.Administration.Catalog;

using SIPO.Library.Enum;
using SIPO.Web.Support;

using System.Text;

using Newtonsoft.Json.Linq;
namespace SIPO.Web.AjaxHandler.Transaction
{
    public class recJurnalhandler : BaseHandler
    {
        private recJurnalRepo JurnalDal = new recJurnalRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
     
        
        private string MethodName = string.Empty;
        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];
            try
            {
                context.Response.Clear();
                context.Response.Buffer = true;

                System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

                string jsonString = string.Empty;
                jsonString = context.Server.UrlDecode(sr.ReadToEnd());
                JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

                sr.Close();
                sr.Dispose();
            }
            catch { 
            }
            switch (MethodName.ToLower())
            {
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                     case ("update"):
                    context.Response.Write(UpdateIsSaiko(context));
                    break;
                case ("getdatasummary"):
                    context.Response.Write(GetDataSummary(context));
                    break;
                case ("getdatasummarydet"):
                    context.Response.Write(GetDataSummaryDet(context));
                    break;
                case ("getdatadetail"):
                    context.Response.Write(GetDataDetail(context));
                    break;
            }
            context.Response.Flush();
            context.Response.End();
        }

        private string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context); ;

            //DateTime? periodeAwal = context.Request["periodeawal"].Equals(string.Empty) ? (DateTime?)null : Helper.FormatDate(context.Request["periodeawal"], Helper.Culture.Indonesian);
            //DateTime? periodeAkhir = context.Request["periodeakhir"].Equals(string.Empty) ? (DateTime?)null : Helper.FormatDate(context.Request["periodeakhir"], Helper.Culture.Indonesian);
            //// int debtorID = context.Request["DebtorID"].Equals(string.Empty) ? 0 : int.Parse(context.Request["DebtorID"].ToString());

            //////konversi tanggal
            //string sPeriodeAwal = periodeAwal == null ? string.Empty : string.Format("{0:yyyyMMdd}", periodeAwal);
            //string sPeriodeAkhir = periodeAkhir == null ? string.Empty : string.Format("{0:yyyyMMdd}", periodeAkhir);
            if (!context.Request["periodeawal"].Equals("") && !context.Request["periodeakhir"].Equals(""))
            {
                parameters += "where tgl_trans between '" + context.Request["periodeawal"] + "' and '" + context.Request["periodeakhir"] + "'";
            }

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? "tgl_posting" : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recJurnal> pagedList = null;

            try
            {
                
                    totalCount = Convert.ToInt32(JurnalDal.SelectScalar(SQL.Function.Aggregate.Count, recJurnal.Fields.JurnalID, parameters));
                    decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                    totalPages = Convert.ToInt32(dc);
                    pagedList = JurnalDal.GetList(pageSize, page, sidx, sord, parameters);
               
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetDataJurnal";
                log.LogMessage = ex.Message;
                log.LogSource = "recJurnalhander.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }


            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

        private string GetDataDetail(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context); ;

            string id = context.Request.Params["id"];
            string status = context.Request.Params["IsSummary"];
            if (status != null && status != "")
            {
                parameters += "where jurnalcode in (select jurnalcode from transactions.recJurnal where postinggroup ='" + status + "')";
            }
            else
            {
                parameters += "where JurnalCode ='" + id + "'";
            }
                int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recJurnalDetail.Fields.JurnalDetailID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recJurnalDetail> pagedList = null;

            try
            {

                totalCount = Convert.ToInt32(JurnalDal.SelectScalarDetail(SQL.Function.Aggregate.Count, recJurnalDetail.Fields.JurnalDetailID, parameters));
                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);
                pagedList = JurnalDal.GetListDetail(pageSize, page, sidx, sord, parameters);

            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetDataDetailJurnal";
                log.LogMessage = ex.Message;
                log.LogSource = "recJurnalhander.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }


            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

        private string GetDataSummary(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context); ;

            string post = context.Request["posting"].ToString();
            
            //DateTime? periodeAwal = context.Request["periodeawal"].Equals(string.Empty) ? (DateTime?)null : Helper.FormatDate(context.Request["periodeawal"], Helper.Culture.Indonesian);
            //DateTime? periodeAkhir = context.Request["periodeakhir"].Equals(string.Empty) ? (DateTime?)null : Helper.FormatDate(context.Request["periodeakhir"], Helper.Culture.Indonesian);
            //// int debtorID = context.Request["DebtorID"].Equals(string.Empty) ? 0 : int.Parse(context.Request["DebtorID"].ToString());

            //////konversi tanggal
            //string sPeriodeAwal = periodeAwal == null ? string.Empty : string.Format("{0:yyyyMMdd}", periodeAwal);
            //string sPeriodeAkhir = periodeAkhir == null ? string.Empty : string.Format("{0:yyyyMMdd}", periodeAkhir);
            //if (!context.Request["periodeawal"].Equals("") && !context.Request["periodeakhir"].Equals(""))
            //{
            //    parameters += "where PostingDate between '" + context.Request["periodeawal"] + "' and '" + context.Request["periodeakhir"] + "'";
            //}
            parameters += "where a.postinggroup = '" + post + "' and a.istosaiko = 0";
            
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? "c.coatypenmae" : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recJurnalSummary> pagedList = null;

            try
            {

                totalCount = Convert.ToInt32(JurnalDal.SelectScalarSummary(SQL.Function.Aggregate.Count, "a.coatype", parameters));
                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);
                pagedList = JurnalDal.GetListSummary(pageSize, page, sidx, sord, parameters,totalCount);

            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetDataJurnalSummary";
                log.LogMessage = ex.Message;
                log.LogSource = "recJurnalhander.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }


            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

        private string GetDataSummaryDet(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context); ;



            //DateTime? periodeAwal = context.Request["periodeawal"].Equals(string.Empty) ? (DateTime?)null : Helper.FormatDate(context.Request["periodeawal"], Helper.Culture.Indonesian);
            //DateTime? periodeAkhir = context.Request["periodeakhir"].Equals(string.Empty) ? (DateTime?)null : Helper.FormatDate(context.Request["periodeakhir"], Helper.Culture.Indonesian);
            //// int debtorID = context.Request["DebtorID"].Equals(string.Empty) ? 0 : int.Parse(context.Request["DebtorID"].ToString());

            //////konversi tanggal
            //string sPeriodeAwal = periodeAwal == null ? string.Empty : string.Format("{0:yyyyMMdd}", periodeAwal);
            //string sPeriodeAkhir = periodeAkhir == null ? string.Empty : string.Format("{0:yyyyMMdd}", periodeAkhir);
            //if (!context.Request["periodeawal"].Equals("") && !context.Request["periodeakhir"].Equals(""))
            //{
            //    parameters += "where PostingDate between '" + context.Request["periodeawal"] + "' and '" + context.Request["periodeakhir"] + "'";
            //}
            string post = context.Request["postgroup"].ToString();
            if (post != null || post != "")
            {
                parameters += "where postinggroup ='" + post + "'";
            }
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? "postinggroup" : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recJurnalSummary> pagedList = null;

            try
            {

                totalCount = Convert.ToInt32(2);
                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(1);
                pagedList = JurnalDal.GetListSummDetail(pageSize, page, sidx, sord, parameters);

            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetDataJurnalSummaryDetail";
                log.LogMessage = ex.Message;
                log.LogSource = "recJurnalhander.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }


            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }
        private string UpdateIsSaiko(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            StringBuilder sb = new StringBuilder();

            try
            {
                var PostingGroup = (context.Request.Params["id"].ToString());

                int hasil =  JurnalDal.UpdateIsTosaiko(PostingGroup);
                if (hasil > 0)
                {
                    helper.IsSuccess = true;
                    helper.Message = "Data berhasil di posting !";
                }
                else
                {
                    helper.IsSuccess = false;
                    helper.Message = "Gagal posting saiko !";
                }
                }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Posting Saiko";
                log.LogMessage = helper.Message;
                log.LogSource = "Jurnalhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

           
                return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }
        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}